package com.star.eastern.blee.fragments


import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AlertDialog
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.star.eastern.blee.MainActivity
import com.star.eastern.blee.R
import com.star.eastern.blee.customview.HdmiViewItem
import com.star.eastern.blee.utils.Tripple7BluetoothCommandProtocol
import com.tangula.android.utils.ApplicationUtils
import com.tangula.android.utils.SharedPreferencesUtils
import com.tangula.android.utils.TaskUtils
import com.tangula.android.utils.ToastUtils
import java.lang.Exception
import java.util.*


@Suppress("NAME_SHADOWING")
class SwitchPage : Fragment() {
    private var iterm1: HdmiViewItem? = null
    private var iterm2: HdmiViewItem? = null
    private var iterm3: HdmiViewItem? = null
    private var iterm4: HdmiViewItem? = null
    private var disconnect: Button? = null
    private var apply: Button? = null
    private var autoswitch: RadioGroup? = null
    private var off: RadioButton? = null
    private var on: RadioButton? = null
    private var devicetitle: TextView? = null
    private var devicename: TextView? = null
    private var state: Int? = null

    private var wantAsw = -1


    private fun updateDeviceName() {

        onError2Scan {
            //Log.v("console", "update device name")
            val name = Tripple7BluetoothCommandProtocol.getDeviceName()
            //Log.v("console", "device name:$name")
            TaskUtils.runInUiThread {
                if (devicetitle != null) {
                    devicetitle!!.text = name
                }
            }
        }

    }

    fun onStatusUpdate(stat:String){
        try {
            val st = stat.removePrefix("STAT")
            if (Tripple7BluetoothCommandProtocol.isAutoSwitchOn(st)) {
                //Log.v("console", "auto switch status is on")
                if(wantAsw<0) {
                    autoswitch?.check(R.id.offer)
                }else if(wantAsw==1){
                    wantAsw = -1
                }
            } else {
                //Log.v("console", "auto switch status is off")
                if(wantAsw<0) {
                    autoswitch?.check(R.id.search)
                }else if(wantAsw==0){
                    wantAsw = -1
                }
            }
            val idx = Tripple7BluetoothCommandProtocol.getStatHdmi(st).toInt() - 1
            val hdmis = listOf(iterm1, iterm2, iterm3, iterm4)
            hdmis.forEachIndexed { i, item ->
                if (idx == i) {
                    item?.setViewPanBackgroundColor(resources.getColor(R.color.normalButtonPressed))
                } else {
                    item?.setViewPanBackgroundColor(resources.getColor(R.color.normalButtonDisabled))
                }
            }
        }catch (e:Exception){
            Log.e("console", e.localizedMessage, e)
            Thread{
                Thread.sleep(2000)
                updateStatus()
            }.start()
        }
    }

    private fun updateStatus() {

        val hdmis = listOf(iterm1, iterm2, iterm3, iterm4)
        fun changeHdmiStatus(idx:Int){
            hdmis.forEachIndexed { i, item ->
                try {
                    if (idx == i) {
                        item?.setViewPanBackgroundColor(resources.getColor(R.color.normalButtonPressed))
                    } else {
                        item?.setViewPanBackgroundColor(resources.getColor(R.color.normalButtonDisabled))
                    }
                }catch (e:Exception){
                    Log.w("console", e.localizedMessage, e)
                }
            }
        }

        onError2Scan {
            //Log.v("console", "switch page update status")
            Tripple7BluetoothCommandProtocol.sendCmdSTAT({ stat ->
                //Log.v("console", "response status is $stat")
                val st = stat.removePrefix("STAT")
                if (Tripple7BluetoothCommandProtocol.isAutoSwitchOn(st)) {
                    //Log.v("console", "auto switch status is on")
                    autoswitch?.check(R.id.offer)
                } else {
                    //Log.v("console", "auto switch status is off")
                    autoswitch?.check(R.id.search)
                }

                val idx = Tripple7BluetoothCommandProtocol.getStatHdmi(st).toInt() - 1
                changeHdmiStatus(idx)

            }) {
                //Log.v("console", "stat fail")
            }


            updateDeviceName()

        }

    }


    @SuppressLint("NewApi", "SetTextI18n")
    override fun onCreateView(inflater: LayoutInflater, parent: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Defines the xml file for the fragment
        val view = inflater.inflate(R.layout.switch_layout, parent, false)
        iterm1 = view.findViewById(R.id.vw_switch_item1)
        iterm2 = view.findViewById(R.id.vw_switch_item2)
        iterm3 = view.findViewById(R.id.vw_switch_item3)
        iterm4 = view.findViewById(R.id.vw_switch_item4)
        disconnect = view.findViewById(R.id.btn_disconnect)
        apply = view.findViewById(R.id.btn_apply)
        autoswitch = view.findViewById<View>(R.id.vw_switch_button).findViewById(R.id.toggle)
        off = autoswitch!!.findViewById(R.id.search)
        on = autoswitch!!.findViewById(R.id.offer)
        devicetitle = view.findViewById(R.id.tv_devicetitle)
        devicename = view.findViewById(R.id.et_devicename)


        iterm1!!.setHdmiNameText(
            SharedPreferencesUtils.getStringPrivate(
                ApplicationUtils.APP,
                Tripple7BluetoothCommandProtocol.getDeviceAddress(),
                "s1",
                "HDMI1"
            )
        )


        //-----------on send s1 s2 s3 s4 command response, to update buttons color.-------------
        val hdmis = listOf(iterm1, iterm2, iterm3, iterm4)
        fun changeHdmiStatus(idx:Int){
            hdmis.forEachIndexed { i, item ->
                if (idx == i) {
                    item?.setViewPanBackgroundColor(resources.getColor(R.color.normalButtonPressed))
                } else {
                    item?.setViewPanBackgroundColor(resources.getColor(R.color.normalButtonDisabled))
                }
            }
        }
        //------------end-------------

        iterm1!!.setOnClickListener {
            onError2Scan {
                Tripple7BluetoothCommandProtocol.sendCmdS1({
                    updateStatus()
                    //changeHdmiStatus(0)
                }) {
                    updateStatus()
                }
            }
        }
        iterm1!!.setOnLongClickListener {
            alertEdit(iterm1!!, 1)
            false
        }


        iterm2!!.setHdmiNameText(
            SharedPreferencesUtils.getStringPrivate(
                ApplicationUtils.APP, Tripple7BluetoothCommandProtocol.getDeviceAddress(),
                "s2", "HDMI2"
            )
        )
        iterm2!!.setOnClickListener {
            onError2Scan {
                Tripple7BluetoothCommandProtocol.sendCmdS2({
                    updateStatus()
                }) {
                    updateStatus()
                }
            }
        }
        iterm2!!.setOnLongClickListener {
            alertEdit(iterm2!!, 2)
            false
        }

        iterm3!!.setHdmiNameText(
            SharedPreferencesUtils.getStringPrivate(
                ApplicationUtils.APP, Tripple7BluetoothCommandProtocol.getDeviceAddress(),
                "s3", "HDMI3"
            )
        )
        iterm3!!.setOnClickListener {
            //changeHdmiStatus(2)
            onError2Scan {
                Tripple7BluetoothCommandProtocol.sendCmdS3({
                    updateStatus()
                }) {
                    updateStatus()
                }
            }
        }
        iterm3!!.setOnLongClickListener {
            alertEdit(iterm3!!, 3)
            false
        }

        iterm4!!.setHdmiNameText(
            SharedPreferencesUtils.getStringPrivate(
                ApplicationUtils.APP, Tripple7BluetoothCommandProtocol.getDeviceAddress(),
                "s4", "HDMI4"
            )
        )
        iterm4!!.setOnClickListener {
            //changeHdmiStatus(3)
            onError2Scan {
                Tripple7BluetoothCommandProtocol.sendCmdS4({
                    updateStatus()
                }) {
                    updateStatus()
                }
            }

        }
        iterm4!!.setOnLongClickListener {
            alertEdit(iterm4!!, 4)
            false
        }
        disconnect!!.setOnClickListener {
            if (disconnect!!.text == "RECONNECT") {
                (this.activity as MainActivity).switch2SwitchControlPage()
                disconnect!!.text = "DISCONNECT"
            } else {
                Tripple7BluetoothCommandProtocol.disconnect()
                val act = (activity as MainActivity)
                act.enableScanTab()
                act.disableSwitchAndAvDeviceTab()
                act.switch2BleScanPage()
                disconnect!!.text = "RECONNECT"
            }

        }

        apply!!.setOnClickListener {
            val imm = (activity as MainActivity)
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(this.devicename!!.getWindowToken(), 0)
            var text = devicename!!.text.toString()
            text = text.substring(0, if (text.length < 12) text.length else 12)
            onError2Scan {
                Tripple7BluetoothCommandProtocol.sendCmdDeviceName(text, {
                    TaskUtils.runInUiThread {
                        devicetitle?.text = text
                        devicename?.text = ""
                    }
                }) {}

            }
        }


        devicename!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, start: Int, before: Int, after: Int) {

            }

            override fun onTextChanged(charSequence: CharSequence, starrt: Int, before: Int, after: Int) {

            }

            override fun afterTextChanged(editable: Editable) {

                if (devicename!!.length() >= 1) {
                    //到1位时是蓝色
                    apply!!.setBackgroundColor(resources.getColor(R.color.button_negative))
                } else {
                    //没到1位是灰色
                    apply!!.setBackgroundColor(resources.getColor(R.color.normalButtonDisabled))
                }

                if (devicename!!.length() >= 12) {
                    ToastUtils.showToastShort(getString(R.string.max_text))
                }
            }

        })



        autoswitch!!.setOnCheckedChangeListener { group, checkedId ->
            onError2Scan {
                if (checkedId == R.id.offer) {
                    //Log.v("console", "string is A $checkedId")
                    wantAsw = 1
                    Tripple7BluetoothCommandProtocol.sendCmdASW1({  }) {}
                } else {
                    //Log.v("console", "string is A $checkedId")
                    wantAsw = 0
                    Tripple7BluetoothCommandProtocol.sendCmdASW0({  }) {}
                }
            }
        }


        devicetitle = view.findViewById(R.id.tv_devicetitle)



        devicename = view.findViewById(R.id.et_devicename)
        devicename?.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {

                val inputManager = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                inputManager.hideSoftInputFromWindow(devicename!!.getWindowToken(), 0)
                inputManager.showSoftInput(devicename!!, InputMethodManager.SHOW_FORCED)
                return false
            }

        })

        return view


    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        updateStatus()
    }



    @SuppressLint("InflateParams")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    fun alertEdit(view: HdmiViewItem, index: Int) {
        val v = layoutInflater.inflate(R.layout.item_text, null)
        val vwText = v.findViewById<TextView>(R.id.vw_name_text)
        vwText.hint = view.HdmiNameText()
        val dialog = AlertDialog.Builder(Objects.requireNonNull<FragmentActivity>(this.activity))
            .setTitle(R.string.alert_edit_hdmi_name)
            .setView(v)
            .setPositiveButton("ok") { dialogInterface, i ->
                if (!v.findViewById<EditText>(R.id.vw_name_text).text.toString().isEmpty()) {
                    val text = vwText.text.toString()
                    view.setHdmiNameText(text)
                    SharedPreferencesUtils.putStringPrivateA(
                        ApplicationUtils.APP,
                        Tripple7BluetoothCommandProtocol.getDeviceAddress(),
                        "s$index",
                        text
                    )
                }
            }
            .setNegativeButton("cancel", null)
            .show()
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(resources.getColor(R.color.button_negative))
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(resources.getColor(R.color.button_negative))

    }

    fun onError2Scan(task: () -> Unit) {
        (activity as MainActivity).onError2Scan(task)
    }


}
